import type { Ref } from 'vue'
import { useEventBus, type FloatPaneOptions, eventBus, type FloatPaneContainer } from '@/widgets'

const openFloatPaneEvent = Symbol('open-float-pane')
const activeOrOpenFloatPaneEvent = Symbol('active-open-float-pane')

interface ActiveOrOpenFloatPaneEventData {
  key: string
  opts: () => Omit<FloatPaneOptions, 'key'>
}

export function useFloatPaneContainer(fpc: Ref<InstanceType<typeof FloatPaneContainer>>) {
  useEventBus(openFloatPaneEvent, (opts: FloatPaneOptions) => {
    fpc.value?.openPane(opts)
  })
  useEventBus(activeOrOpenFloatPaneEvent, ({ key, opts }: ActiveOrOpenFloatPaneEventData) => {
    fpc.value?.activeOrOpenPane(key, opts)
  })
}

export function activeOrOpenFloatPane(dat: ActiveOrOpenFloatPaneEventData | FloatPaneOptions) {
  if ('opts' in dat) {
    eventBus.emit(activeOrOpenFloatPaneEvent, dat)
  } else {
    const opts = dat as FloatPaneOptions
    eventBus.emit(activeOrOpenFloatPaneEvent, {
      key: opts.key,
      opts: () => opts
    })
  }
}

export function openFloatPane(opts: FloatPaneOptions) {
  eventBus.emit(openFloatPaneEvent, opts)
}
